package com.yb.guigu.pick.code.generator.listener;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.rabbitmq.client.Channel;
import com.yb.guigu.pick.core.domain.mq.EmailSend;
import com.yb.guigu.pick.mail.sender.bean.MailSenderRequest;
import com.yb.guigu.pick.mail.sender.bean.MailSenderResponse;
import com.yb.guigu.pick.mail.sender.sender.IGuiguMailSender;
import com.yb.guigu.pick.rabbitmq.messager.api.model.MessageContent;
import com.yb.guigu.pick.core.constant.EmailType;
import com.yb.guigu.pick.core.constant.RabbitMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.IOException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/11 21:00
 * FileName: EmailListener
 * Description:
 */

@Component
@Slf4j

public class EmailListener {

    @Autowired
    IGuiguMailSender guiguMailSender;

    @Autowired
    TemplateEngine templateEngine;

   @RabbitListener(queues = RabbitMQConstant.EmailQueueConstant.QUEUE)
    public void handle(@Payload MessageContent<EmailSend> result, Message message, Channel channel) throws IOException {
        try {
            String body = new String(message.getBody());
            log.info("body:{}",body);


            EmailSend emailSend = result.getContent();

            sendEmail(emailSend);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e){

            log.error("EmailListener:{}",e);

            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    private void sendEmail(EmailSend emailSend){

       Context context =new Context();

       context.setVariable("code",emailSend.getCode());

       String content = templateEngine.process("email-code", context);

        MailSenderRequest senderRequest = MailSenderRequest.builder().sendTo(emailSend.getEmail())
                .subject("验证码")
                .type(EmailType.MIME.getName())
                .uuid(emailSend.getUuid())
                .content(content).build();

        log.info("senderRequest:{}",senderRequest);

        MailSenderResponse senderResponse = guiguMailSender.send(senderRequest);

        log.info("senderResponse:{}",senderResponse);

    }

}
